package com.javawiz;

import com.javawiz.config.ActiveMQConfigurer;
import com.javawiz.model.Order;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.*;

import static com.javawiz.config.ActiveMQConfigurer.ORDER_QUEUE;

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderPublisher {

    private final JmsTemplate jmsTemplate;

    public void send(Order myMessage) {
        log.info("sending with convertAndSend() to queue <" + myMessage + ">");
        jmsTemplate.convertAndSend(ORDER_QUEUE, myMessage);

        Destination destination = new ActiveMQTopic(ActiveMQConfigurer.ORDER_TOPIC);
        publish(destination, "hello7777373");
    }

    /**
     * 向指定的topic发布消息
     * https://blog.csdn.net/liuchuanhong1/article/details/72726337
     * spring boot-同时使用jms的Queue(队列)和Topic(发布订阅)
     *
     * @param topic
     * @param msg
     */
    public void publish(final Destination topic, final String msg) {
        jmsTemplate.send(topic, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                System.out.println("topic name 是" + topic.toString()
                        + "，发布消息内容为:\t" + msg);
                return session.createTextMessage(msg);
            }
        });
    }
}